import { ref } from 'vue'
import { defineStore } from 'pinia'

export const useAppStore = defineStore('app', () => {
  // 状态
  const darkMode = ref(false)
  const loading = ref(false)
  const isMobile = ref(false)
  const locale = ref('zh-cn')
  const theme = ref('default')
  const primaryColor = ref('#409eff')
  
  // 全局配置
  const config = ref({
    title: 'Admin2025',
    version: '1.0.0',
    author: 'Admin Team',
    description: '现代化管理系统',
    keywords: ['admin', 'vue3', 'element-plus'],
    copyright: 'Copyright © 2025 Admin Team'
  })

  // 方法
  const setDarkMode = (value) => {
    darkMode.value = value
    localStorage.setItem('darkMode', JSON.stringify(value))
    
    // 应用到DOM
    const html = document.documentElement
    if (value) {
      html.classList.add('dark-mode')
    } else {
      html.classList.remove('dark-mode')
    }
  }

  const toggleDarkMode = () => {
    setDarkMode(!darkMode.value)
  }

  const setLoading = (value) => {
    loading.value = value
  }

  const setMobile = (value) => {
    isMobile.value = value
  }

  const setLocale = (value) => {
    locale.value = value
    localStorage.setItem('locale', value)
  }

  const setTheme = (value) => {
    theme.value = value
    localStorage.setItem('theme', value)
  }

  const setPrimaryColor = (color) => {
    primaryColor.value = color
    localStorage.setItem('primaryColor', color)
    
    // 应用主题色到CSS变量
    document.documentElement.style.setProperty('--el-color-primary', color)
  }

  const initFromStorage = () => {
    // 初始化暗色模式
    const savedDarkMode = localStorage.getItem('darkMode')
    if (savedDarkMode !== null) {
      setDarkMode(JSON.parse(savedDarkMode))
    }

    // 初始化语言
    const savedLocale = localStorage.getItem('locale')
    if (savedLocale) {
      locale.value = savedLocale
    }

    // 初始化主题
    const savedTheme = localStorage.getItem('theme')
    if (savedTheme) {
      theme.value = savedTheme
    }

    // 初始化主题色
    const savedPrimaryColor = localStorage.getItem('primaryColor')
    if (savedPrimaryColor) {
      setPrimaryColor(savedPrimaryColor)
    }

    // 检测是否为移动设备
    checkMobile()
    window.addEventListener('resize', checkMobile)
  }

  const checkMobile = () => {
    isMobile.value = window.innerWidth <= 768
  }

  const resetSettings = () => {
    setDarkMode(false)
    setLocale('zh-cn')
    setTheme('default')
    setPrimaryColor('#409eff')
  }

  return {
    // 状态
    darkMode,
    loading,
    isMobile,
    locale,
    theme,
    primaryColor,
    config,
    
    // 方法
    setDarkMode,
    toggleDarkMode,
    setLoading,
    setMobile,
    setLocale,
    setTheme,
    setPrimaryColor,
    initFromStorage,
    resetSettings
  }
})
